import { ref, onMounted } from 'vue'

function debounce(fn:any, delay = 100) {
    let timer:any = null
    return () => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        fn()
      }, delay)
    }
  }
  
export function useKeyboardHeight() {
  const keyboardHeight = ref(0)
    // #ifdef H5
  const originalHeight = ref(window.innerHeight)
    // #endif

  function handleResize() {
    const diff = originalHeight.value - window.innerHeight
    keyboardHeight.value = Math.max(diff, 0)
  }

  onMounted(() => {
    // #ifdef H5
    window.addEventListener('resize',  debounce(handleResize))
    // #endif

    // #ifndef H5
    uni.onKeyboardHeightChange(res => {
      keyboardHeight.value = res.height || 0
    })
    // #endif
  })

  return { keyboardHeight }
}